<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>订单结算 - 水果超市</title>
  <link rel="stylesheet" href="/css/style.css">
</head>
<body>
  <div id="app" v-cloak>
    <!-- 页面头部 -->
    <div class="header">
      <div class="container clearfix">
        <h1>📝 订单结算</h1>
        <div class="header-actions">
          <a href="/index.html" class="btn btn-default">返回首页</a>
        </div>
      </div>
    </div>

    <!-- 主内容区 -->
    <div class="container">
      <!-- 功能建设中提示 -->
      <div class="card text-center" style="margin-bottom: 20px;">
        <div style="padding: 60px 20px;">
          <div style="font-size: 80px; margin-bottom: 20px;">🚧</div>
          <h2 style="color: #409eff; margin-bottom: 15px;">订单结算功能正在建设中</h2>
          <p style="color: #909399; font-size: 16px; margin-bottom: 30px;">
            我们正在努力开发订单管理功能，敬请期待！
          </p>
          <div>
            <a href="/index.html" class="btn btn-primary btn-lg">返回首页</a>
            <a href="/cart.html" class="btn btn-default btn-lg" style="margin-left: 10px;">返回购物车</a>
          </div>
        </div>
      </div>

      <!-- 以下内容暂时隐藏 -->
      <div style="display: none;">
      <!-- 加载状态 -->
      <div v-if="loading" class="loading">
        处理中...
      </div>

      <!-- 订单创建成功，等待支付 -->
      <div v-else-if="order && order.status === 'PENDING_PAYMENT'">
        <div class="card">
          <div class="card-header">订单详情</div>
          <div class="card-body">
            <!-- 订单号 -->
            <div class="summary-row">
              <span>订单号：</span>
              <span style="font-family: monospace;">{{ order.id }}</span>
            </div>
            <div class="summary-row" v-if="order.receiptNumber">
              <span>小票号：</span>
              <span style="font-family: monospace;">{{ order.receiptNumber }}</span>
            </div>
            <div class="divider"></div>

            <!-- 订单商品明细 -->
            <div style="margin: 20px 0;">
              <h3 style="font-size: 16px; margin-bottom: 10px;">商品明细</h3>
              <div v-for="item in order.items" :key="item.id" style="padding: 10px 0; border-bottom: 1px solid #ebeef5;">
                <div style="display: flex; justify-content: space-between; align-items: center;">
                  <div style="flex: 1;">
                    <div style="font-weight: bold;">{{ item.productName }}</div>
                    <div style="font-size: 12px; color: #909399;">
                      {{ formatQuantity(item.quantity.value, item.quantity.unitName || item.quantity.unit) }} 
                      × {{ formatMoney(item.unitPrice) }}/{{ item.baseUnit }}
                    </div>
                    <!-- 单位换算说明 -->
                    <div v-if="item.normalizedQuantity && item.normalizedQuantity != item.quantity.value" 
                         style="font-size: 12px; color: #67c23a;">
                      换算后：{{ formatQuantity(item.normalizedQuantity, item.baseUnit) }}
                    </div>
                    <!-- 折扣说明 -->
                    <div v-if="item.lineBeforeDiscount && item.lineAfterDiscount && item.lineBeforeDiscount > item.lineAfterDiscount" 
                         style="font-size: 12px; color: #f56c6c;">
                      折扣前：{{ formatMoney(item.lineBeforeDiscount) }} 
                      → 折扣后：{{ formatMoney(item.lineAfterDiscount) }}
                    </div>
                  </div>
                  <div style="font-size: 16px; font-weight: bold;">
                    {{ formatMoney(item.lineAfterDiscount || item.lineTotal) }}
                  </div>
                </div>
              </div>
            </div>

            <div class="divider"></div>

            <!-- 金额汇总 -->
            <div class="order-summary">
              <div class="summary-row">
                <span>商品小计：</span>
                <span>{{ formatMoney(order.subtotal) }}</span>
              </div>
              <div class="summary-row" v-if="order.discountTotal && order.discountTotal > 0">
                <span>优惠折扣：</span>
                <span class="text-success">-{{ formatMoney(order.discountTotal) }}</span>
              </div>
              <div class="divider"></div>
              <div class="summary-row total">
                <span>应付金额：</span>
                <span>{{ formatMoney(order.payableAmount) }}</span>
              </div>
            </div>

            <!-- 促销规则说明 -->
            <div v-if="order.appliedPromotions && order.appliedPromotions.length > 0" class="mt-20">
              <h3 style="font-size: 14px; margin-bottom: 10px;">已应用优惠：</h3>
              <div v-for="promo in order.appliedPromotions" :key="promo.id" style="margin-bottom: 5px;">
                <span class="badge badge-danger">{{ promo.name }}</span>
                <span style="font-size: 12px; color: #909399; margin-left: 10px;">
                  {{ promo.description || '' }}
                </span>
              </div>
            </div>

            <!-- 操作按钮 -->
            <div class="mt-20">
              <button class="btn btn-default" @click="goBackToCart" style="width: 30%;">
                返回修改
              </button>
              <button class="btn btn-success btn-lg" @click="payOrder" style="width: 68%; margin-left: 2%;">
                确认支付 {{ formatMoney(order.payableAmount) }}
              </button>
            </div>
          </div>
        </div>
      </div>

      <!-- 支付成功 -->
      <div v-else-if="order && order.status === 'PAID'">
        <div class="card text-center">
          <div style="padding: 50px;">
            <div style="font-size: 64px; color: #67c23a;">✅</div>
            <h2 style="color: #67c23a; margin: 20px 0;">支付成功！</h2>
            
            <div class="order-summary" style="margin: 30px auto; max-width: 400px;">
              <div class="summary-row">
                <span>订单号：</span>
                <span style="font-family: monospace;">{{ order.id }}</span>
              </div>
              <div class="summary-row" v-if="order.receiptNumber">
                <span>小票号：</span>
                <span style="font-family: monospace;">{{ order.receiptNumber }}</span>
              </div>
              <div class="summary-row">
                <span>支付金额：</span>
                <span class="text-danger" style="font-size: 20px; font-weight: bold;">
                  {{ formatMoney(order.payableAmount) }}
                </span>
              </div>
              <div class="summary-row" v-if="order.paymentTime">
                <span>支付时间：</span>
                <span>{{ formatDateTime(order.paymentTime) }}</span>
              </div>
            </div>

            <div class="mt-20">
              <a href="/index.html" class="btn btn-primary btn-lg">继续购物</a>
              <button class="btn btn-default btn-lg ml-10" @click="viewOrderDetail">查看订单详情</button>
            </div>
          </div>
        </div>
      </div>

      <!-- 订单已取消 -->
      <div v-else-if="order && order.status === 'CANCELLED'">
        <div class="card text-center">
          <div style="padding: 50px;">
            <div style="font-size: 64px; color: #909399;">❌</div>
            <h2 style="color: #909399; margin: 20px 0;">订单已取消</h2>
            <div class="mt-20">
              <a href="/index.html" class="btn btn-primary">返回首页</a>
            </div>
          </div>
        </div>
      </div>

      <!-- 初始状态：显示购物车预览并创建订单 -->
      <div v-else>
        <div class="card text-center">
          <div style="padding: 50px;">
            <div style="font-size: 48px;">🛒</div>
            <h3 style="margin: 20px 0;">准备创建订单...</h3>
            <button class="btn btn-primary btn-lg" @click="createOrder">
              立即下单
            </button>
            <a href="/cart.html" class="btn btn-default btn-lg ml-10">
              返回购物车
            </a>
          </div>
        </div>
      </div>
      </div>
      <!-- 隐藏内容结束 -->
    </div>
  </div>

  <!-- 引入依赖 -->
  <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  <script src="/js/config.js"></script>
  <script src="/js/utils.js"></script>
  <script src="/js/api.js"></script>

  <!-- 页面脚本 -->
  <script>
    const { createApp } = Vue;

    createApp({
      data() {
        return {
          loading: false,
          order: null,
          cartId: null,
        };
      },
      
      mounted() {
        // 从URL获取购物车ID或订单ID
        this.cartId = getQueryParam('cartId');
        const orderId = getQueryParam('orderId');
        
        if (orderId) {
          // 如果有订单ID，加载订单详情
          this.loadOrder(orderId);
        } else if (this.cartId) {
          // 如果有购物车ID，自动创建订单
          this.createOrder();
        } else {
          // 都没有，使用默认购物车
          this.cartId = getCartId();
        }
      },
      
      methods: {
        /**
         * 创建订单
         */
        async createOrder() {
          this.loading = true;
          try {
            const cartId = this.cartId || getCartId();
            
            // 调用结算接口
            const result = await API.checkout({
              cartId: cartId
            });
            this.order = result.data;
            
            console.log('订单创建成功：', this.order);
            
            // 更新URL，添加orderId参数
            setQueryParam('orderId', this.order.id);
            
          } catch (error) {
            showError(error);
            // 创建订单失败，返回购物车
            setTimeout(() => {
              window.location.href = '/cart.html';
            }, 2000);
          } finally {
            this.loading = false;
          }
        },
        
        /**
         * 加载订单详情
         */
        async loadOrder(orderId) {
          this.loading = true;
          try {
            const result = await API.getOrderById(orderId);
            this.order = result.data;
            console.log('订单加载成功：', this.order);
          } catch (error) {
            showError(error);
          } finally {
            this.loading = false;
          }
        },
        
        /**
         * 支付订单
         */
        async payOrder() {
          if (!this.order || !this.order.id) {
            showError(new Error('订单信息不存在'));
            return;
          }
          
          if (!confirm(`确认支付 ${formatMoney(this.order.payableAmount)} 吗？`)) {
            return;
          }
          
          this.loading = true;
          try {
            // 调用支付接口
            const payResult = await API.payOrder(this.order.id, {
              paymentMethod: 'CASH' // 简化处理，实际应该选择支付方式
            });
            this.order = payResult.data;
            
            console.log('支付成功：', payResult);
            
            // 重新加载订单以获取最新状态
            await this.loadOrder(this.order.id);
            
            showSuccess('支付成功！');
            
            // 清空本地购物车ID
            clearCartId();
            
          } catch (error) {
            showError(error);
          } finally {
            this.loading = false;
          }
        },
        
        /**
         * 返回购物车
         */
        goBackToCart() {
          window.location.href = '/cart.html';
        },
        
        /**
         * 查看订单详情
         */
        viewOrderDetail() {
          alert('订单详情查看功能待实现\n订单号：' + this.order.id);
        },
        
        /**
         * 格式化金额
         */
        formatMoney(amount) {
          return formatMoney(amount);
        },
        
        /**
         * 格式化数量
         */
        formatQuantity(value, unit) {
          return formatQuantity(value, unit);
        },
        
        /**
         * 格式化日期时间
         */
        formatDateTime(datetime) {
          return formatDateTime(datetime);
        },
      }
    }).mount('#app');
  </script>
</body>
</html>

